const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database();

exports.main = async (event, context) => {
  try {
    // 创建集合
    try {
      await db.createCollection('sales');
      console.log('创建集合成功');
    } catch (err) {
      console.log('集合已存在或创建失败:', err);
    }

    // 先清空集合中的数据
    try {
      await db.collection('sales').where({}).remove();
      console.log('清空原有数据成功');
    } catch (err) {
      console.log('清空数据失败:', err);
    }

    // 添加新数据
    const salesData = [
      { region: '华东', city: '上海', sales: 11 },
      { region: '华东', city: '南京', sales: 11 },
      { region: '华南', city: '广州', sales: 22 },
      { region: '华南', city: '深圳', sales: 22 }
    ];

    for (const item of salesData) {
      try {
        await db.collection('sales').add({
          data: item
        });
        console.log(`添加数据成功: ${item.city}`);
      } catch (err) {
        console.error(`添加数据失败 ${item.city}:`, err);
        throw err;
      }
    }

    return {
      code: 200,
      msg: '数据添加成功',
      success: true
    };
  } catch (e) {
    console.error('执行失败:', e);
    return {
      code: 500,
      msg: e.message || '执行失败',
      success: false
    };
  }
};
